package com.easyedu.gateway.Filter;

import com.alibaba.fastjson.JSONObject;
import com.easyedu.core.util.JwtUtils;
import com.easyedu.core.util.R;
import com.easyedu.core.util.ResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author lmr
 **/
@Component
public class IdentityFilter implements GlobalFilter, Ordered {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    private static final String TOKEN = "token";

    private final JwtUtils jwtUtils = new JwtUtils();

    @Order(1)
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if (path.equals("/root/login") || path.equals("/root/logon") || path.equals("/root/check/user/name")
                || path.equals("/root/check/user/number")) {
            return chain.filter(exchange);
        }
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(TOKEN);
        LOGGER.info("[token] " + token);
        String level = jwtUtils.getMsgFromJwt(token).get("level");
        LOGGER.info("账号等级：" + level);

        //学生允许访问学生和选课系统
        if (level.equals("4") && (path.startsWith("/student") || path.startsWith("/selection"))) {
            return chain.filter(exchange);
        } else {
            redirect(response, "不符合权限", "/root/login");
        }

        //老师允许访问学生、老师、文件系统
        if (level.equals("3") && (path.startsWith("/student") || path.startsWith("/teacher") ||
                path.startsWith("/file"))) {
            return chain.filter(exchange);
        } else {
            redirect(response, "不符合权限", "/student/index");
        }

        //教务处允许访问学生、老师、教务、文件、选课系统
        if (level.equals("2") && (path.startsWith("/student") || path.startsWith("/teacher") || path.startsWith(
                "/dean") || path.startsWith("/file") || path.startsWith("/selection"))) {
            return chain.filter(exchange);
        } else {
            redirect(response, "不符合权限", "/teacher/index");
        }

        //超级管理员全部允许
        if (level.equals("1")) {
            return chain.filter(exchange);
        } else {
            redirect(response, "不符合权限", "/root/login");
        }

        redirect(response, "不符合权限", "/root/login");
        return null;
    }

    private DataBuffer redirect(ServerHttpResponse response, String msg, String redirectUrl) {
        return response.bufferFactory().wrap(JSONObject.toJSONBytes(R.error(ResponseCode.REDIRECT).message(msg).data(
                "url", redirectUrl)));
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
